package com.qiyun.dinghuohui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.support.multidex.MultiDexApplication;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.qiyun.dinghuohui.activity.MainSyncFailureActivity;
import com.qiyun.dinghuohui.base.BaseActivity;
import com.qiyun.dinghuohui.common.ApiName;
import com.qiyun.dinghuohui.common.ClientCookie;
import com.qiyun.dinghuohui.common.CommonDataSets;
import com.qiyun.dinghuohui.http.HttpUtils;
import com.qiyun.dinghuohui.service.ManagerService;
import com.qiyun.dinghuohui.utils.CommonUtil;
import com.qiyun.dinghuohui.utils.DateUtil;
import com.qiyun.dinghuohui.utils.JsonBuilder;
import com.qiyun.dinghuohui.utils.JsonParamInfoReturn;
import com.qiyun.dinghuohui.utils.LogDebug;
import com.qiyun.dinghuohui.utils.PublicActivityManager;
import com.qiyun.dinghuohui.utils.ServerResponse;
import com.qiyun.dinghuohui.utils.Utils;
import com.qiyun.dinghuohui.utils.WifiAdmin;
import com.qiyun.dinghuohui.vo.WifiControlRecordInfoBean;
import com.qiyun.dinghuohui.vo.WifiInfoBean;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import java.util.zip.GZIPInputStream;

/**
 * Created by xlm on 2018\5\25 0025
 */

public class ApplicationDataHolder extends MultiDexApplication {

    private static Stack<Activity> mActivitys;
    private static ApplicationDataHolder mApp;
    private String[] memo;

    public int wifiCurrentIndex = 0;
    public List<WifiInfoBean> wifiList = new ArrayList<WifiInfoBean>();
    public int wifiLastNetId = -1;
    public String wifiLastSsid = "";

    public final String VERSIONFORAUTO = "dhh_android_2013092900";// 当前版本
    // 用于自动更新判断
    // 偶数为正式片，奇数为测试
    // 指示是否可以自动下载基础资料
    public boolean downloadBaseInfo = true;
    // 代码
    public final static String gc_code_flag_3 = "3分";// 死款不订
    public final static String gc_code_flag_5 = "5分";// 5分(不好) 基本款订一点
    public final static String gc_code_flag_7 = "7分";// 7分(一般) 不错能卖
    public final static String gc_code_flag_10 = "10分";// 10分(好) 爆款
    public final static String gc_size_null = "!@#";// 订货配置尺寸空值

    public final static String tiao_model_signle = "单位跳转";
    public final static String tiao_model_double = "双位跳转";
    public final static String tiao_model_no = "不自动跳转";

    public final static String C_AnalysisTYPE_FLAG = "AnalysisTYPE";

    public final static String C_AnalysisTYPE_JIJIE = "0"; // 季节
    public final static String C_AnalysisTYPE_XILEI = "1"; // 系列
    public final static String C_AnalysisTYPE_BODUAN = "2";// 波段
    public final static String C_AnalysisTYPE_LEIBEI = "3";// 类别
    public final static String C_AnalysisTYPE_KUANSHI = "4";// 款式
    public final static String C_AnalysisTYPE_SEXI = "5";// 色系
    public final static String C_AnalysisTYPE_CHIMA = "6";// 尺码
    public final static String C_AnalysisTYPE_JIAGEDAI = "7";// 价格带
    public final static String C_AnalysisTYPE_GL = "8";// 货品等级

    // 综合分析
    public final static int c_AnalysisByComprehensive_SerialWave = 1;
    public final static int c_AnalysisByComprehensive_Type = 2;
    public final static int c_AnalysisByComprehensive_Color = 3;
    public final static int c_AnalysisByComprehensive_Price = 4;

    // 订单提交参数 完成率参数
    public boolean ordercommit = false;
    public int orderCommitAmount = 0;// 金额
    public int orderCommitCount = 0;// 数量
    public int orderCommitStyle = 0;// 款量
    public int orderCommitMustStyle = 0;// 必定款量
    public int orderCommitMustCount = 0;// 必定数量

    private int planamount = 0;// 计划金额
    private int plancount = 0;// 计划数量
    private int planstyle = 0;// 计划款量
    public int planmuststyle = 0; // 必定款款量
    public int planmustcount = 0;// 必定款数量

    public final static String c_TableCssStyleDefine_Head = "color:#FFFFFF; background-color:#17375e; text-align:center;padding:4px; font-weight:bold;";
    public final static String c_TableCssStyleDefine_Item1 = "color:#000000; background-color:#92d050; text-align:center;padding:4px;";
    public final static String c_TableCssStyleDefine_Item2 = "color:#000000; background-color:#8eb4e3; text-align:center;padding:4px;";
    public final static String html_css = "body{font-size:12px}\n"
            + ".clear{ clear:both}\n"
            + ".divitem{float:left; text-align:center; padding:4px; }\n"
            + ".divitem a{ text-decoration:none;}\n"
            + ".divitemmain{background-color:#FFFFFF; margin-left:auto;margin-right:auto; border-radius:8px; border:1px solid #9bbb59;line-height:20px;}\n"
            + ".divitemimg{ width:128px; height:128px;}\n"
            + ".divitemlabel{ font-weight:bold; font-size:16px; color:#0000FF; text-decoration:none; padding:0 3px;}\n"
            + ".textleft{ text-align:left;}\n"
            + ".textright{ text-align:right}\n"
            + "table th{padding:3px;background-color:#008403;color:#FFFFFF;border-left:1px dotted #FFFFFF;font-size:13px;line-height:16px}\n"
            + "table tr td{padding:0 2px;font-size:12px}\n"
            + ".tbl{text-align:center;border-right:1px dotted #008403;line-height:30px;}\n"
            + ".tbl .first{border-left:1px dotted #008403;}\n"
            + ".tbl tbody tr{ background-color:#FFFFFF; }\n"
            + ".tbl tbody tr td{border-bottom:1px dotted #008403;border-left:1px dotted #008403;}\n"
            + ".tbl tbody tr:hover{background-color:#FC730B;}\n"
            + ".tbl tbody .foot td{background-color:#006423;border-bottom:1px dotted #008403;border-left:1px dotted #FFFFFF;}\n"
            + ".tbl tfoot tr td{background-color:#008443;border-bottom:1px dotted #FFFFFF;border-left:1px dotted #FFFFFF;}\n"
            + ".content_inner_pagenum{ clear:both;height: 30px; padding: 6px;border-top:1px solid #008403;margin-top:6px;}\n"
            + ".pagenum { text-align: right; float:right; }\n"
            + ".pagenum .currentpageselect { float:left; padding:2px 5px 2px 5px; font-size:10.5pt; font-weight:bold; color:#FF6633; background: #FFD8F8  ; border:1px solid #878d59; text-align:center; margin:0 2px;}\n"
            + ".pagenum .currentpageselect a:hover { font-size:10.5pt; font-weight:bold; color:#FF6633; }\n"
            + ".pagenum .currentpageselect a:visited { font-size:10.5pt; font-weight:bold; color:#FF6633; }\n"
            + ".pagenum .currentpageselect a:link { font-size:10.5pt; font-weight:bold; color:#FF6633; padding:0 3px; }\n"
            + ".pagenum .currentpageselect a:active { font-size:10.5pt; font-weight:bold; color:#FF6633; }\n"
            + ".pagenum .currentpageunselect { float:left; padding:2px 5px 2px 5px; font-size:10.5pt; color:#000000; background: #E8F8E8; border:1px solid #878d59; text-align:center; margin:0 2px; }\n"
            + ".pagenum .currentpageunselect a:hover { font-size:10.5pt; color:#FF6633; }\n"
            + ".pagenum .currentpageunselect a:visited { font-size:10.5pt; color:#000000; }\n"
            + ".pagenum .currentpageunselect a:link { font-size:10.5pt; color:#000000; padding:0 3px;}\n"
            + ".pagenum .currentpageunselect a:active { font-size:10.5pt; color:#FF6633; }\n"
            + ".pagenum .currentpageunselect2 { float:left; padding:2px 5px 2px 5px; font-size:10.5pt; color:#000000; background: #E8F8E8; border:1px solid #008403; text-align:center; margin:0 2px; }\n"
            + ".pagenum .currentpageunselect2 a:hover { font-size:10.5pt; color:#FF6633; }\n"
            + ".pagenum .currentpageunselect2 a:visited { font-size:10.5pt; color:#000000; }\n"
            + ".pagenum .currentpageunselect2 a:link { font-size:10.5pt; color:#000000; }\n"
            + ".pagenum .currentpageunselect2 a:active { font-size:10.5pt; color:#FF6633; }";

    private String logFile = "";

    public String getLogFile() {
        logFile = CommonDataSets.CLIENT_STRONGPATH + "/errordhh.txt";
        return logFile;
    }

    // 报表权限
    public boolean REPORT_WCL = true;
    public boolean REPORT_SEASON = true;
    public boolean REPORT_SERIAL = true;
    public boolean REPORT_WAVE = true;
    public boolean REPORT_TYPE = true;
    public boolean REPORT_STYLE = true;
    public boolean REPORT_COLOR = true;
    public boolean REPORT_SIZE = true;
    public boolean REPORT_PRICE = true;
    public boolean REPORT_GOODSLEVEL = true;
    public boolean REPORT_BANDS = true;
    public boolean REPORT_BANDSGL = true;
    public boolean OrderInputConfigModify = true;// 订货配置比例可修改
    // AD权限
    public boolean AD_SHOWALLCOUNT = true;
    public boolean AD_SHOWALLAMOUNT = true;
    private String boardInfo_allowBrand = ""; // 允许显示的品牌
    private String userRegion;
    @SuppressLint("StaticFieldLeak")
    public static Login mLoginActivity;

    @Override
    public void onCreate() {
        super.onCreate();
        mApp = this;
        newActivityStack();
        //CrashHandler crashHandler = CrashHandler.getInstance();
        //crashHandler.init(getApplicationContext());
        // 初始化自定义Activity管理器
        activityManager = PublicActivityManager.getScreenManager();
        // 注册crashHandler
        // 注册一个接受广播类型
        batteryBR = new BatteryBroadcastReceiver();
        batteryIntentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(batteryBR, batteryIntentFilter);
        // 启动后台
        startShopOrderService();
    }

    /**
     * 获取application实例
     *
     * @return
     */
    public static ApplicationDataHolder getApp() {
        return mApp;
    }

    /**
     * 结束所有activity
     */
    private void finishAllActivity() {
        while (!mActivitys.isEmpty()) {
            mActivitys.pop().finish();
        }
    }

    /**
     * 退出application
     */
    public void exitApplication(boolean needbackground) {
        finishAllActivity();
        if (!needbackground) {
            System.exit(0);
        }
    }

    /**
     * 创建activity栈
     */
    private void newActivityStack() {
        if (mActivitys == null) {
            mActivitys = new Stack<Activity>();
        }
    }

    /**
     * 添加一个activity
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        if (!mActivitys.contains(activity)) {
            mActivitys.add(activity);
        }
    }

    /**
     * 获取activity栈
     *
     * @return
     */
    public Stack<Activity> getActivityStack() {
        return mActivitys;
    }

    /**
     * 结束栈顶activity
     */
    public void finishTop() {
        if (!mActivitys.isEmpty()) {
            mActivitys.pop().finish();
        }
    }

    /**
     * 移除一个activity
     *
     * @param activity
     */
    public void removeActivity(Activity activity) {
        if (mActivitys.contains(activity)) {
            mActivitys.remove(activity);
        }
    }

    /**
     * 日志标签
     */
    public static final String TAGWRITELOGS = "WriteLogs";

    /**
     * 自定义日志（tag过滤：WriteLogs）
     *
     * @param format 日志内容
     */
    public static synchronized void Trace(String format) {
        Log.d(TAGWRITELOGS, format == null ? "Error: null String!!!" : format);
    }

    public String[] getMemo() {
        return memo;
    }

    public void setMemo(String[] memo) {
        this.memo = memo;
    }

    private boolean online = false;

    public boolean isOnline() {
        return online;
    }

    public void setOnline(boolean online) {
        this.online = online;
    }

    // WIFI控制记录
    public WifiControlRecordInfoBean wifiControlRecordInfoBean = new WifiControlRecordInfoBean();

    // 判断有无网络
    public boolean CheckNetworkActivity() {
        boolean b_Connected = false;
        try {// 检测WIFI
            ConnectivityManager mConnectivity = (ConnectivityManager) getApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            TelephonyManager mTelephony = (TelephonyManager) getApplicationContext()
                    .getSystemService(Context.TELEPHONY_SERVICE);
            // 检查网络连接，如果无网络可用，就不需要进行连网操作等
            NetworkInfo info = mConnectivity.getActiveNetworkInfo();
            if (info == null || !mConnectivity.getBackgroundDataSetting()) {
                b_Connected = false;
            } else {
                // 判断网络连接类型，只有在3G或wifi里进行一些数据更新。
                int netType = -1;
                int netSubtype = -1;
                try {
                    netType = info.getType();
                    netSubtype = info.getSubtype();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (netType == ConnectivityManager.TYPE_WIFI) {
                    b_Connected = info.isConnected();// WIFI网络
                } else if (netType == ConnectivityManager.TYPE_MOBILE
                        && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
                        && !mTelephony.isNetworkRoaming()) {
                    b_Connected = info.isConnected(); // 3G网络
                } else {
                    b_Connected = info.isConnected();// 其它网络
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        setOnline(b_Connected);
        return b_Connected;
    }

    // wifi控制
    public WifiAdmin getWifiAdmin() {
        WifiAdmin wifiAdmin = new WifiAdmin(this);
        return wifiAdmin;
    }

    public void getWifiAdminOpen() {
        getWifiAdmin().openWifi();
    }

    public void getWifiAdminClose() {
        if (CommonDataSets.ds_config_activity.netOpenMinute > 0) {// 0为实时
            getWifiAdmin().closeWifi();
        }
    }

    // 保存当前的网络ID
    public void wifiSaveNetId() {
        wifiLastNetId = getWifiAdmin().getNetworkId();
        wifiLastSsid = getWifiAdmin().getSSID();
        if (wifiLastSsid == null) {
            wifiLastSsid = "";
        }
    }

    // 检测并等待打开网络
    public boolean checkOpenWifi() {
        boolean bSucc = true;
        int waittimecount = 0;
        while (getWifiAdmin().checkState() != WifiManager.WIFI_STATE_ENABLED) {
            waittimecount++;
            if (waittimecount > 40) {
                bSucc = false;
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return bSucc;
    }

    // 软引用
    private static HashMap<String, SoftReference<Bitmap>> imageCache = new HashMap<String, SoftReference<Bitmap>>();

    public static void getLoacalBitmapClear(String url) {
        if (imageCache.containsKey(url)) {
            imageCache.remove(url);
        }
    }

    // 读取图片并解密
    public static Bitmap getLoacalBitmap(String url, int size) {
        // Log.d("TAG", "Pic url->"+url);
        final String c_encryption_BeginFlag = "BIBEI";
        FileInputStream fis;
        byte[] buffer;
        boolean picIsEncryption = false;
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inInputShareable = true;
        options.inPurgeable = true;// 设置图片可以被回收
        options.inSampleSize = size;

        if (imageCache.containsKey(url)) {
            bitmap = imageCache.get(url).get();
            if (bitmap != null) {
                return bitmap;
            }
        }
        try {
            File file = new File(url);
            if (file.exists()) {
                fis = new FileInputStream(url);
                buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 判断有无加密
                if (buffer.length > 9) {
                    byte[] b = new byte[5];
                    b[0] = buffer[0];
                    b[1] = buffer[1];
                    b[2] = buffer[2];
                    b[3] = buffer[3];
                    b[4] = buffer[4];
                    String sBStr = new String(b);
                    if (sBStr.trim().equals(c_encryption_BeginFlag)) {
                        picIsEncryption = true;
                    }
                }
                if (picIsEncryption) {
                    byte bs;
                    int iKey = 165;
                    byte[] bufferout = new byte[buffer.length - 5];
                    for (int i = 0; i < bufferout.length; i++) {
                        // XOR 165 ( 1010 0101 )
                        bs = buffer[i + 5];
                        bs = (byte) (bs ^ iKey);
                        buffer[i] = bs;
                    }
                    bitmap = BitmapFactory.decodeByteArray(buffer, 0,
                            buffer.length, options);
                    imageCache.put(url, new SoftReference<Bitmap>(bitmap));
                    return bitmap;
                } else {
                    bitmap = BitmapFactory.decodeByteArray(buffer, 0,
                            buffer.length, options);
                    imageCache.put(url, new SoftReference<Bitmap>(bitmap));
                    return bitmap;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 取得未压缩图片 (大图)
     *
     * @param url
     * @return
     */
    public static Bitmap getOriginLocalBitmap(String url) {
        // Log.d("TAG", "Pic url->"+url);
        final String c_encryption_BeginFlag = "BIBEI";
        FileInputStream fis;
        byte[] buffer;
        boolean picIsEncryption = false;
        Bitmap bitmap = null;
        try {
            File file = new File(url);
            if (file.exists()) {
                fis = new FileInputStream(url);
                buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 判断有无加密
                if (buffer.length > 9) {
                    byte[] b = new byte[5];
                    b[0] = buffer[0];
                    b[1] = buffer[1];
                    b[2] = buffer[2];
                    b[3] = buffer[3];
                    b[4] = buffer[4];
                    String sBStr = new String(b);
                    if (sBStr.trim().equals(c_encryption_BeginFlag)) {
                        picIsEncryption = true;
                    }
                }
                if (picIsEncryption) {
                    byte bs;
                    int iKey = 165;
                    byte[] bufferout = new byte[buffer.length - 5];
                    for (int i = 0; i < bufferout.length; i++) {
                        // XOR 165 ( 1010 0101 )
                        bs = buffer[i + 5];
                        bs = (byte) (bs ^ iKey);
                        buffer[i] = bs;
                    }
                    bitmap = BitmapFactory.decodeByteArray(buffer, 0,
                            buffer.length);
                    imageCache.put(url, new SoftReference<Bitmap>(bitmap));
                    return bitmap;
                } else {
                    bitmap = BitmapFactory.decodeByteArray(buffer, 0,
                            buffer.length);
                    imageCache.put(url, new SoftReference<Bitmap>(bitmap));
                    return bitmap;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将图片缩放到指定大小
     *
     * @param bitmap
     * @param w
     * @return
     */
    public synchronized static Bitmap scaleBitmap(Bitmap bitmap, float w) {
        if (bitmap == null) {
            return null;
        }

        try {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Matrix matrix = new Matrix();
            float scaleW = w / (float) width;
            matrix.postScale(scaleW, scaleW);
            if (width > 0 && height > 0) {
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                        matrix, true);
            }
            return bitmap;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public void setBoardInfo_allowBrand(String boardInfo_allowBrand) {
        this.boardInfo_allowBrand = boardInfo_allowBrand;
    }

    public boolean checkReportPopToast(Context context, boolean bReporType) {
        if (!bReporType) {
            Utils.makeToastInfo(context, "此功能暂未开放");
        }
        return bReporType;
    }

    private String serverUrl;// 通讯地址
    private boolean testcommandlink = false; // 用于标记是否需要测试通讯 登录成功后置为TRUE
    private int testaccount = 1;

    public boolean isTestcommandlink() {
        return testcommandlink;
    }

    public void setTestcommandlink(boolean testcommandlink) {
        this.testcommandlink = testcommandlink;
        if (this.testcommandlink) {
        } else {
        }
    }

    public int getTestaccount() {
        return testaccount;
    }

    public void setTestaccount(int testaccount) {
        this.testaccount = testaccount;
    }

    private ManagerService managerService;

    public ManagerService getManagerService() {
        return managerService;
    }

    public void setManagerService(ManagerService managerService) {
        this.managerService = managerService;
    }

    // 用户订货配置
    private int sizemaxcount = 9;

    public int getSizemaxcount() {
        return sizemaxcount;
    }

    public void setSizemaxcount(int sizemaxcount) {
        this.sizemaxcount = sizemaxcount;
        if (getSizeinputjumpflag() < 0) {
            if (this.sizemaxcount <= 9) {
                setSizeinputjumpflag(0);
            } else if (this.sizemaxcount <= 99) {
                setSizeinputjumpflag(1);
            } else {
                setSizeinputjumpflag(9);
            }
        }
    }

    // 用户主界面提示内容
    private boolean login = false;

    public boolean isLogin() {
        return login;
    }

    public void setLogin(boolean login) {
        this.login = login;
    }

    private boolean canReadRefrushBackData = false;

    public boolean isCanReadRefrushBackData() {
        return canReadRefrushBackData;
    }

    public void setCanReadRefrushBackData(boolean canReadRefrushBackData) {
        this.canReadRefrushBackData = canReadRefrushBackData;
    }

    // 控制跳转
    private int sizeinputjumpflag = -1; // -1未设定 0单位跳 1双位跳 9不限制

    public int getSizeinputjumpflag() {
        return sizeinputjumpflag;
    }

    public void setSizeinputjumpflag(int sizeinputjumpflag) {
        this.sizeinputjumpflag = sizeinputjumpflag;
    }

    // 手动更新资料时间控制
    private Date fileUpdateHandleLastDate = new Date();

    public Date getFileUpdateHandleLastDate() {
        return fileUpdateHandleLastDate;
    }

    public void setFileUpdateHandleLastDate(Date fileUpdateHandleLastDate) {
        this.fileUpdateHandleLastDate = fileUpdateHandleLastDate;
    }

    private boolean saveOrderRealTime = false;// 标记是否实时,AD及总代则为实时

    public boolean isSaveOrderRealTime() {
        checkSaveOrderRealTime();
        return saveOrderRealTime;
    }

    private void setSaveOrderRealTime(boolean saveOrderRealTime) {
        this.saveOrderRealTime = saveOrderRealTime;
    }

    public void checkSaveOrderRealTime() {
        if (getUserType() == 1 || getLevel().toUpperCase().equals("A")) {
            setSaveOrderRealTime(true);
        } else {
            Log.d("", "CommonDataSets.ds_config_activity.netOpen->"
                    + CommonDataSets.ds_config_activity.netOpen + "   ::"
                    + CommonDataSets.ds_config_activity.netOpenMinute);
            if (CommonDataSets.ds_config_activity.netOpen) {
                setSaveOrderRealTime(false);
            } else {
                setSaveOrderRealTime(CommonDataSets.ds_config_activity.netOpenMinute == 0);
            }
        }
    }

    public boolean saveOrderCalcTime = false; // 计算时间
    public Date saveOrderBeginTime = new Date(); // 开始计时时间
    public int saveOrderFailCount = 0;

    public void saveOrderFlagEnabled(boolean enabled) {// 设置标识
        if (enabled) {
            if (!saveOrderCalcTime) {
                saveOrderFailCount = 0;
                saveOrderBeginTime = new Date();
            }
            saveOrderCalcTime = true;
        } else {
            saveOrderFailCount = 0;
            saveOrderCalcTime = false;
        }
    }

    // 切换次数为2次，如果2次依然不能成功，则跳出提示，需要手动解决，并终止客户的其他操作
    public boolean saveOrderFaileCountTip() {
        if (CommonDataSets.ds_config_activity.updatefail) {
            return saveOrderFailCount >= CommonDataSets.ds_config_activity.updatefailcount;
        }
        return false;
    }

    // 通知接口
    private NotificationManager notificationManager;// 通知区域内容
    private Object mInfoDlg;

    public NotificationManager getNotificationManager() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return notificationManager;
    }

    // 提示锁定屏
    @SuppressWarnings("deprecation")
    public void showEmptyBatteryDlg() {
        Activity acti = activityManager.currentActivity().instance;
        if (acti == null || acti instanceof Login)
            return;
        ((BaseActivity) acti).AppDialogShow(BaseActivity.DLG);
    }

    // 超过失败次数进行提示
    public void saveOrderFaileCountTipShowActivity() {
        // 当前Activity
        Intent intent = null;
        if (MainActivity.instance == null) {
            intent = new Intent(activityManager.currentActivity(), MainSyncFailureActivity.class);
            activityManager.currentActivity().startActivity(intent);
        } else {
            intent = new Intent(MainActivity.instance, MainSyncFailureActivity.class);
            MainActivity.instance.startActivity(intent);
        }
        /*
         * long when = System.currentTimeMillis(); // 获取当前时间 //新建一个通知，指定其图标和标题
		 * Notification notification = new Notification(R.drawable.icon,
		 * "上传失败,请联系工作人员!", when);//创建一个通知。第一个参数为图标,第二个参数为标题,第三个为通知时间
		 * notification.defaults = Notification.DEFAULT_SOUND;//设置通知发出的默认声音
		 * //PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0,
		 * openintent, 0);//当点击消息时就会向系统发送openintent意图 PendingIntent
		 * contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
		 * notification.setLatestEventInfo(this,"上传失败,请联系工作人员!","上传失败,请联系工作人员!",
		 * contentIntent);//给通知设置最新的事件信息
		 * getNotificationManager().notify(R.drawable.icon, notification);
		 */
    }

    public void notificationManagerCancel(int notificationId) {
        getNotificationManager().cancel(notificationId);
    }

    // 用户主界面提示内容
    private String board_info = "";
    private String boardInfo_name = "";
    private String boardInfo_comments = "";
    private String boardInfo_budget = "";
    private String boardInfo_groupname = "";

    public String getBoard_info() {
        return board_info;
    }

    public void setBoard_info(String boardInfo) {
        board_info = boardInfo;
    }

    public String getBoardInfo_name() {
        return boardInfo_name;
    }

    public void setBoardInfo_name(String boardInfoName) {
        boardInfo_name = boardInfoName;
    }

    public String getBoardInfo_comments() {
        return boardInfo_comments;
    }

    public void setBoardInfo_comments(String boardInfoComments) {
        boardInfo_comments = boardInfoComments;
    }

    public String getBoardInfo_budget() {
        return boardInfo_budget;
    }

    public void setBoardInfo_budget(String boardInfoBudget) {
        boardInfo_budget = boardInfoBudget;
    }

    public String getBoardInfo_groupname() {
        return boardInfo_groupname;
    }

    public void setBoardInfo_groupname(String boardInfoGroupname) {
        boardInfo_groupname = boardInfoGroupname;
    }

    // 载入的系统配置
    private int sc_Wifiid = 0;
    private String sc_Brand_Tip = "";// 品牌提示
    private String sc_Brand_PassWord = "";// 品牌管理密码
    private String sc_Brand_Memo = "";// 品牌说明
    private int sc_Brand_PicShowCount = 0;// 产品陈列数量

    private int Pic_Mode = 0;
    private String regionStr;
    // 同步时间窗口
    private Date sync_windowstime_begin = new Date();

    public Date getSync_windowstime_begin() {
        return sync_windowstime_begin;
    }

    public void setSync_windowstime_begin(Date syncWindowstimeBegin) {
        sync_windowstime_begin = syncWindowstimeBegin;
    }

    public Date getSync_windowstime_end() {
        return sync_windowstime_end;
    }

    public int getPic_Mode() {
        return Pic_Mode;
    }

    public void setPic_Mode(int pic_Mode) {
        Pic_Mode = pic_Mode;
    }

    public void setSync_windowstime_end(Date syncWindowstimeEnd) {
        sync_windowstime_end = syncWindowstimeEnd;
    }

    private Date sync_windowstime_end = DateUtil.addDaysToDate(new Date(), 5);

    public int getSc_Brand_PicShowCount() {
        return sc_Brand_PicShowCount;
    }

    public void setSc_Brand_PicShowCount(int scBrandPicShowCount) {
        sc_Brand_PicShowCount = scBrandPicShowCount;
    }

    public int getSc_Wifiid() {
        return sc_Wifiid;
    }

    public void setSc_Wifiid(int scWifiid) {
        sc_Wifiid = scWifiid;
    }

    public String getSc_Brand_Tip() {
        return sc_Brand_Tip;
    }

    public void setSc_Brand_Tip(String scBrandTip) {
        sc_Brand_Tip = scBrandTip;
    }

    public String getRegionStr() {
        return regionStr;
    }

    public void setRegionStr(String regionStr) {
        this.regionStr = regionStr;
    }

    public String getSc_Brand_PassWord() {
        return sc_Brand_PassWord;
    }

    public void setSc_Brand_PassWord(String scBrandPassWord) {
        sc_Brand_PassWord = scBrandPassWord;
    }

    public String getSc_Brand_Memo() {
        return sc_Brand_Memo;
    }

    public void setSc_Brand_Memo(String scBrandMemo) {
        sc_Brand_Memo = scBrandMemo;
    }

    public int getPlanamount() {
        return planamount;
    }

    public void setPlanamount(int planamount) {
        this.planamount = planamount;
    }

    public int getPlancount() {
        return plancount;
    }

    public void setPlancount(int plancount) {
        this.plancount = plancount;
    }

    public int getPlanstyle() {
        return planstyle;
    }

    public void setPlanstyle(int planstyle) {
        this.planstyle = planstyle;
    }

    // 系统保存常量
    private static final String USER_NAME = "__user_name__";
    private static final String USER_TYPE = "__user_type__";
    private static final String USER_GROUP = "__user_group__";
    private static final String USER_PASS = "__user_pass__";
    private static final String USER_LEVEL = "__user_level__";
    private static final String PRIVILEGE = "__privilege__";

    // 当前
    public int brandId = 0;// 品牌ID
    public String brandName = "";// 品牌名称
    private String accountName = "";// 账号名称
    private String accountRegion = "";// 区域
    private String accountRegionBig = "";// 大区
    private int account_jhjlb = 0;// 进货价类别

    public String getAccountRegionBig() {
        return accountRegionBig;
    }

    public void setAccountRegionBig(String accountRegionBig) {
        this.accountRegionBig = accountRegionBig;
    }

    public int getAccount_jhjlb() {
        return account_jhjlb;
    }

    public void setAccount_jhjlb(int accountJhjlb) {
        account_jhjlb = accountJhjlb;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public String getAccountRegion() {
        return accountRegion;
    }

    public void setAccountRegion(String accountRegion) {
        this.accountRegion = accountRegion;
    }

    private int sysinfo_battery = 0; // 当前电池电量
    private String sysinfo_deviceId = "";

    public String getDeviceId() {// Context context
        try {
            if (sysinfo_deviceId == null) {
                sysinfo_deviceId = "";
            }
            if ("".equals(sysinfo_deviceId)) {
                sysinfo_deviceId = getWifiMacAddress();
                // final TelephonyManager tm = (TelephonyManager)
                // getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
                // sysinfo_deviceId=tm.getDeviceId();
            }
        } catch (Exception e) {
        }
        return sysinfo_deviceId;
    }

    // 获得无线网卡MAC地址
    public String getWifiMacAddress() {
        WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        Log.d("wifi", "wifi mac address->" + info.getMacAddress());
        return info.getMacAddress();
    }

    // 检测当前连接的网络是否在列表内
    public boolean checkNetInList() {
        String connSsid = getWifiAdmin().getSSID();
        boolean bFind = false;
        for (WifiInfoBean wb : wifiList) {
            if (wb.ssid.equals(connSsid)) {
                bFind = true;
                break;
            }
        }
        return bFind;
    }


    public String getBattery() {
        return sysinfo_battery + "";
    }

    private static Map<String, Object> store = new HashMap<String, Object>();

    public String getServerUrl(boolean hasOnLine, int ut, String userLevel) {
        // 这里进行判断
        if (ut == 1) {
            return CommonDataSets.ds_config_activity.httpanaly;
        }
        if (hasOnLine && "A".equals(userLevel)) {
            return CommonDataSets.ds_config_activity.httpanaly;
        }
        return serverUrl;
    }

    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    private ManagerService mainSyncService = null;
    private Intent intentServiceOrder = null;
    private ServiceConnection connectionSync = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mainSyncService = ((ManagerService.MainSyncBind) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mainSyncService = null;
        }
    };

    public void startShopOrderService() {
        if (intentServiceOrder == null) {
            Log.v("", "App startShopOrderService  Create   connectionOrder==null");
            intentServiceOrder = new Intent(this, ManagerService.class);
            bindService(intentServiceOrder, connectionSync,
                    Context.BIND_AUTO_CREATE);
            startService(intentServiceOrder);

        }
    }

    public void stopShopOrderService() {
        if (intentServiceOrder != null) {
            Log.v("", " App stopShopOrderService");
            unbindService(connectionSync);
            stopService(intentServiceOrder);
            intentServiceOrder = null;
        }
    }

    // public Map<String, String> getSelectedGood() {
    // return selectedGood;
    // }
    //
    // public void setSelectedGood(Map<String, String> selectedGood) {
    // this.selectedGood = selectedGood;
    // }
    //
    // public String[] from;
    //
    // public String[] getFrom() {
    // return from;
    // }
    //
    // public void setFrom(String[] from) {
    // this.from = from;
    // }

    public void setCookie(String key, Object value) {
        store.put(key, value);
    }

    public Object getCookie(String key) {
        return store.get(key);
    }

    public void setUsername(String username) {
        setCookie(USER_NAME, username);
    }

    public String getUsername() {
        String susername = (String) getCookie(USER_NAME);
        if (susername == null) {
            susername = "";
        }
        return susername;
    }

    public String getUserRegion() {
        return userRegion;
    }

    public void setUserRegion(String userRegion) {
        this.userRegion = userRegion;
    }

    public void setUserType(Integer usertype) {
        setCookie(USER_TYPE, usertype);
    }

    public int getUserType() {
        try {
            Integer iut = (Integer) getCookie(USER_TYPE);
            if (iut == null) {
                return 0;
            }
            return iut.intValue();
        } catch (Exception e) {
        }
        return 0;
    }

    public void setUserGroup(String usergroup) {
        setCookie(USER_GROUP, usergroup);
    }

    public String getUserGroup() {
        return (String) getCookie(USER_GROUP);
    }

    public String getPassword() {
        return (String) getCookie(USER_PASS);
    }

    public void setPassword(String password) {
        setCookie(USER_PASS, password);
    }

    public void setPrivilege(Map<String, String> privilege) {
        setCookie(PRIVILEGE, privilege);
    }

    public String getLevel() {
        if (getCookie(USER_LEVEL) == null) {
            return "";
        }
        return (String) getCookie(USER_LEVEL);
    }

    public void setLevel(String level) {
        setCookie(USER_LEVEL, level);
    }

    public BatteryBroadcastReceiver batteryBR = null;
    private IntentFilter batteryIntentFilter = null;

    // public void restrarRegisterBatteryReceiver() {
    // unregisterReceiver(batteryBR);
    // registerReceiver(batteryBR, batteryIntentFilter);
    // }

    @Override
    public void onTerminate() {
        // TODO Auto-generated method stub
        stopShopOrderService();
        super.onTerminate();
    }

    // 锁屏相关
    private DevicePolicyManager policyManager = null;
    private ComponentName componentName;

	/*
     * public DevicePolicyManager getPolicyManager(){ if (policyManager==null){
	 * //获取设备管理服务 policyManager = (DevicePolicyManager)
	 * getSystemService(Context.DEVICE_POLICY_SERVICE); componentName = new
	 * ComponentName(this, AdminReceiver.class); } return policyManager; }
	 */

    /**
     * 接受电量改变广播
     */
    class BatteryBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra("level", 0);
            int scale = intent.getIntExtra("scale", 100);
            sysinfo_battery = (level * 100 / scale);
            if (sysinfo_battery < 10) {
                showEmptyBatteryDlg();
            }
        }
    }

    // TODO:处理返回
    public final static String responseCallFileTip = "获取数据失败";

    public static JsonParamInfoReturn paramCheckByReturn(ServerResponse response) {
        JsonParamInfoReturn jsonParamInfoReturn = new JsonParamInfoReturn();
        try {
            jsonParamInfoReturn.setParam(response.result);
            jsonParamInfoReturn.setParam_aliay(jsonParamInfoReturn.getParam()
                    .getBoolean(JsonBuilder.JSON_YX));
            jsonParamInfoReturn.setParam_op(jsonParamInfoReturn.getParam()
                    .getString(JsonBuilder.JSON_OP));
            jsonParamInfoReturn.setParam_un(jsonParamInfoReturn.getParam()
                    .getString(JsonBuilder.JSON_UN));
            try {
                jsonParamInfoReturn.setParam_ut(jsonParamInfoReturn.getParam()
                        .getInt(JsonBuilder.JSON_UT));
            } catch (Exception e) {
            }
            jsonParamInfoReturn.setCommunicationsWindowClientBegin(DateUtil
                    .convertStringToDate(
                            DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS,
                            jsonParamInfoReturn.getParam().getString(
                                    JsonBuilder.JSON_CWB)));
            jsonParamInfoReturn.setCommunicationsWindowClientEnd(DateUtil
                    .convertStringToDate(
                            DateUtil.DATE_FORMAT_YYYYMMDDHHMMSS,
                            jsonParamInfoReturn.getParam().getString(
                                    JsonBuilder.JSON_CWE)));
            jsonParamInfoReturn.setParam_message(jsonParamInfoReturn.getParam()
                    .getString(JsonBuilder.JSON_MSG));
            jsonParamInfoReturn.setParam_json(jsonParamInfoReturn.getParam()
                    .getJSONObject(JsonBuilder.JSON_Json));
        } catch (Exception e) {
            jsonParamInfoReturn.setParam_aliay_net(false);
            jsonParamInfoReturn.setParam_aliay(false);
            e.printStackTrace();
        }
        return jsonParamInfoReturn;
    }

    public void CheckOffLine(String oldmac) {
        if (CommonDataSets.ds_config_activity.clientcheck) {
            if (oldmac.equals(getWifiMacAddress())) {
                new AlertDialog.Builder(activityManager.currentActivity())
                        .setTitle("强行下线")
                        .setMessage("您的账号已经另一台设备上登录，确认后退出")
                        .setPositiveButton("确认退出",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        getWifiAdminOpen();
                                        android.os.Process
                                                .killProcess(android.os.Process
                                                        .myPid());
                                    }
                                }).show();
            }
        }
    }

    private int networkReadInfoFailCount = 0;// 读到远程文件失败次数
    public boolean bNetExceptShowTip = false;

    public int getNetworkReadInfoFailCount() {
        return networkReadInfoFailCount;
    }

    public void setNetworkReadInfoFailCount(int networkReadInfoFailCount) {
        this.networkReadInfoFailCount = networkReadInfoFailCount;
    }

    public void TerminateApp() {
        if (!bNetExceptShowTip) {
            bNetExceptShowTip = true;
            setNetworkReadInfoFailCount(0);
            stopShopOrderService();
            activityManager.popActivitySaveOne(android.app.Activity.class);
            Login loginAct = (Login) activityManager.currentActivity();
            loginAct.ShowTipNetExcept();
        } else {
            setNetworkReadInfoFailCount(0);
        }
    }

    // 结束退出系统
    private PublicActivityManager activityManager = null;

    public PublicActivityManager getActivityManager() {
        return activityManager;
    }

    public void setActivityManager(PublicActivityManager activityManager) {
        this.activityManager = activityManager;
    }


    // 对文件进行解压缩
    public static boolean GZipUnCompressFile(String inFileName) {
        // 判断这个文件在不在
        boolean bContinue = false;
        String outFileName = inFileName.substring(0, inFileName.length() - 3);
        try {
            File file = new File(inFileName);
            if (file.exists()) {
                bContinue = true;
                FileInputStream fin = new FileInputStream(inFileName); // 得以文件输入流
                GZIPInputStream gzin = new GZIPInputStream(fin); // 得到压缩输入流
                FileOutputStream fout = new FileOutputStream(outFileName); // 得到文件输出流
                byte[] buf = new byte[1024]; // 缓冲区大小
                int num;
                while ((num = gzin.read(buf, 0, buf.length)) != -1) { // 如果文件未读完
                    fout.write(buf, 0, num); // 写入缓冲数据到输出流
                }
                gzin.close(); // 关闭压缩输入流
                fout.close(); // 关闭文件输出流
                fin.close(); // 关闭文件输入流
            } else {
                Log.e("", "文件不存在: " + inFileName);
            }
        } catch (Exception e) {
            bContinue = false;
            Log.e("", "初始化文件失败: " + inFileName);
        }
        return bContinue;
    }

    // 重新读取解压缩文件的内容
    public void readLocalBaseDataToReset() {
        String res = "";
        String encoding = "GB2312";// 文件编码Unicode,UTF-8,ASCII,GB2312,Big5
        BufferedReader bufferedReader;
        String readLineText = null;
        StringBuffer buffer;
        InputStreamReader read;
        JSONObject jsonData;
        try {
            File file = new File(CommonDataSets.CLIENT_STRONGPATH + "/publicbasedata_o");
            if (file.isFile() && file.exists()) {
                buffer = new StringBuffer();
                read = new InputStreamReader(new FileInputStream(file), encoding);
                bufferedReader = new BufferedReader(read);
                try {
                    while ((readLineText = bufferedReader.readLine()) != null) {
                        buffer.append(readLineText.toString().trim());
                    }
                    read.close();
                    res = buffer.toString();
                    // Log.d("", "读取文件成功..."+res);
                    jsonData = new JSONObject(res);
                    // 序列化到内存
                    CommonDataSets.saveToCacheBaseData(jsonData);
                    checkSaveOrderRealTime();
                } catch (IOException e) {
                }
            }
            file = null;
            file = new File(CommonDataSets.CLIENT_STRONGPATH + "/publicbasedata_g");
            if (file.isFile() && file.exists()) {
                buffer = new StringBuffer();
                read = new InputStreamReader(new FileInputStream(file), encoding);
                bufferedReader = new BufferedReader(read);
                try {
                    while ((readLineText = bufferedReader.readLine()) != null) {
                        buffer.append(readLineText.trim());
                    }
                    read.close();
                    res = buffer.toString();
                    // Log.d("", "读取文件成功..."+res);
                    jsonData = new JSONObject(res);
                    // 序列化到内存
                    CommonDataSets.saveToCacheBaseData_g(jsonData);
                } catch (IOException e) {
                }
            }
            file = null;
            file = new File(CommonDataSets.CLIENT_STRONGPATH + "/order_" + getUsername());
            if (file.isFile() && file.exists()) {
                buffer = new StringBuffer();
                read = new InputStreamReader(new FileInputStream(file), encoding);
                bufferedReader = new BufferedReader(read);
                try {
                    while ((readLineText = bufferedReader.readLine()) != null) {
                        buffer.append(readLineText.trim());
                    }
                    read.close();
                    res = buffer.toString();
                    // Log.d("", "读取文件成功..."+res);
                    jsonData = new JSONObject(res);
                    // 序列化到内存
                    CommonDataSets.saveToCacheBaseData_order(jsonData);
                } catch (IOException e) {
                }
            }
            file = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取publicbasedata_o序列化到内存
    private void readLocalBaseDataToReset1() {
        String res = "";
        String encoding = "GB2312";// 文件编码Unicode,UTF-8,ASCII,GB2312,Big5
        BufferedReader bufferedReader;
        String readLineText = null;
        StringBuffer buffer;
        InputStreamReader read;
        JSONObject jsonData;
        try {
            File file = new File(CommonDataSets.CLIENT_STRONGPATH + "/publicbasedata_o");
            if (file.isFile() && file.exists()) {
                buffer = new StringBuffer();
                read = new InputStreamReader(new FileInputStream(file), encoding);
                bufferedReader = new BufferedReader(read);
                try {
                    while ((readLineText = bufferedReader.readLine()) != null) {
                        buffer.append(readLineText.toString().trim());
                    }
                    read.close();
                    res = buffer.toString();

                    jsonData = new JSONObject(res);
                    // 序列化到内存
                    CommonDataSets.saveToCacheBaseData(jsonData);
                    checkSaveOrderRealTime();
                } catch (IOException e) {
                }
            }
            file = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取publicbasedata_g序列化到内存
    private void readLocalBaseDataToReset2() {
        String res = "";
        String encoding = "GB2312";// 文件编码Unicode,UTF-8,ASCII,GB2312,Big5
        BufferedReader bufferedReader;
        String readLineText = null;
        StringBuffer buffer;
        InputStreamReader read;
        JSONObject jsonData;
        try {
            File file = new File(CommonDataSets.CLIENT_STRONGPATH + "/publicbasedata_g");
            if (file.isFile() && file.exists()) {
                buffer = new StringBuffer();
                read = new InputStreamReader(new FileInputStream(file), encoding);
                bufferedReader = new BufferedReader(read);
                try {
                    while ((readLineText = bufferedReader.readLine()) != null) {
                        buffer.append(readLineText.trim());
                    }
                    read.close();
                    res = buffer.toString();
                    jsonData = new JSONObject(res);
                    // 序列化到内存
                    CommonDataSets.saveToCacheBaseData_g(jsonData);
                } catch (IOException e) {
                }
            }
            file = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取order序列化到内存
    private void readLocalBaseDataToReset3() {
        String res = "";
        String encoding = "GB2312";// 文件编码Unicode,UTF-8,ASCII,GB2312,Big5
        BufferedReader bufferedReader;
        String readLineText = null;
        StringBuffer buffer;
        InputStreamReader read;
        JSONObject jsonData;
        try {
            File file = new File(CommonDataSets.CLIENT_STRONGPATH + "/order_" + getUsername());
            if (file.isFile() && file.exists()) {
                buffer = new StringBuffer();
                read = new InputStreamReader(new FileInputStream(file), encoding);
                bufferedReader = new BufferedReader(read);
                try {
                    while ((readLineText = bufferedReader.readLine()) != null) {
                        buffer.append(readLineText.trim());
                    }
                    read.close();
                    res = buffer.toString();
                    jsonData = new JSONObject(res);
                    // 序列化到内存
                    CommonDataSets.saveToCacheBaseData_order(jsonData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            file = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    final String path1 = CommonDataSets.CLIENT_STRONGPATH + "/publicbasedata_o.gz";
    final String path2 = CommonDataSets.CLIENT_STRONGPATH + "/publicbasedata_g.gz";
    private static boolean isDownFlag = false;

    // 下载定时文件
    public boolean downloadBaseFileByServer() {
        downpublicbasedata_o();
        return isDownFlag;
    }

    private void downpublicbasedata_o() {
        HttpUtils.getInstance().loadFile(ClientCookie.getServerUrl() + "/download/publicbasedata_o.gz",
                new HttpUtils.HttpListener() {
                    @Override
                    public void onHttpSuccess(byte[] bytes) {
                        super.onHttpSuccess(bytes);
                        try {
                            final File file = new File(path1);
                            //删除已存在的文件
                            if (file.exists()) {
                                CommonUtil.deleteFile(file);
                            }
                            CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                            GZipUnCompressFile(path1);
                            readLocalBaseDataToReset1();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.d("", "下载文件publicbasedata_o成功  " + path1);
                        downpublicbasedata_g();
                    }
                });

    }

    private void downpublicbasedata_g() {

        HttpUtils.getInstance().loadFile(ClientCookie.getServerUrl() + "/download/publicbasedata_g.gz",
                new HttpUtils.HttpListener() {
                    @Override
                    public void onException(Throwable e) {
                        super.onException(e);
                        LogDebug.e(e);
                    }

                    @Override
                    public void onHttpSuccess(byte[] bytes) {
                        super.onHttpSuccess(bytes);
                        try {
                            final File file = new File(path2);
                            //删除已存在的文件
                            if (file.exists()) {
                                CommonUtil.deleteFile(file);
                            }
                            CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                            GZipUnCompressFile(path2);
                            readLocalBaseDataToReset2();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.d("", "下载文件publicbasedata_g成功  " + path2);
                        down_order();
                    }
                });
    }

    private void down_order() {
        HttpUtils.getInstance().loadFile(ApiName.ORDER_ACCOUNT + getUsername() + ".gz", new HttpUtils.HttpListener() {
            @Override
            public void onHttpSuccess(byte[] bytes) {
                super.onHttpSuccess(bytes);
                try {
                    File file = new File(CommonDataSets.CLIENT_STRONGPATH + "/order_" + getUsername() + ".gz");
                    //删除已存在的文件
                    if (file.exists()) {
                        CommonUtil.deleteFile(file);
                    }
                    CommonUtil.byte2File(bytes, file.getParent(), file.getName());
                    GZipUnCompressFile(CommonDataSets.CLIENT_STRONGPATH + "/order_" + getUsername() + ".gz");
                    readLocalBaseDataToReset3();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Log.d("", "下载文件order_" + getUsername() + "成功");
                isDownFlag = true;
                mLoginActivity.gotoFace();//下载完成跳转主界面
            }
        });
    }










    // 下载文件
    public static boolean downloadPicForServer(final String fileUrl, final String outfilename) {
        HttpUtils.getInstance().loadFile(fileUrl, new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                LogDebug.e(e);
                isDownFlag = false;
            }

            @Override
            public void onHttpSuccess(byte[] bytes) {
                super.onHttpSuccess(bytes);
                final File file = new File(fileUrl);
                try {
                    //删除已存在的文件
                    if (file.exists()) {
                        CommonUtil.deleteFile(file);
                    }
                    CommonUtil.byte2File(bytes, file.getParent(), outfilename);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                isDownFlag = true;
            }
        });
        return isDownFlag;
    }
}

